package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    UserService userService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    OrderDetailService orderDetailService;

    //去支付，生成订单
    @PostMapping("/submit")
    @Transactional
    public R sunmit(@RequestBody Orders orders) {
        //用户id
        Long userId = BaseContext.getCurrentId();
        // 添加查询条件
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, userId);
        //查询购物车信息
        LambdaQueryWrapper<ShoppingCart> shopoingLqw = new LambdaQueryWrapper<>();
        shopoingLqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingList = shoppingCartService.list(shopoingLqw);
        //查询用户数据
        User user = userService.getById(userId);
        //查询地址
        Long addressBookId = orders.getAddressBookId();
        //LambdaQueryWrapper<AddressBook> lqw1 = new LambdaQueryWrapper<>();
        //lqw1.eq(AddressBook::getIsDefault,1);
        //AddressBook one = addressBookService.getOne(lqw1);
        AddressBook addressBook = addressBookService.getById(addressBookId);
     /*   // 订单号
        orders.setUserId(userId);
        orderService.save(orders);
        Long orderId = orders.getId();*/

        long orderId = IdWorker.getId();//订单号
        //总金额
        BigDecimal bigDecimal = new BigDecimal(0);
        //查询订单明细
        for (ShoppingCart shoppingCart : shoppingList) {
            //菜品信息保存到订单明细中
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //    设置ordeid，关联
            orderDetail.setOrderId(orderId);
            //    求金额  数量  *  单价
            BigDecimal amount = shoppingCart.getAmount();

            BigDecimal number = BigDecimal.valueOf(shoppingCart.getNumber());
            //乘法，数量*
            BigDecimal multiply = amount.multiply(number);
            orderDetail.setAmount(multiply);
            //放入bigdecimal  总价
            bigDecimal = bigDecimal.add(multiply);

            //    保存到详细表中
            orderDetailService.save(orderDetail);
        }

        //保存订单数据
        //orders.setId(orderId);
        //     保存创建时间
        orders.setOrderTime(LocalDateTime.now());
        //订单结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //状态
        orders.setStatus(2);
        //
        System.out.println(bigDecimal);
        orders.setAmount(bigDecimal);
        //用户id
        orders.setUserId(userId);
        //  订单号
        orders.setNumber(String.valueOf(orderId));
        //用户名
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //收货人联系电话
        orders.setPhone(addressBook.getPhone());
        //保存收货地址
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
      /*  //收货人
        orders.setConsignee(one.getConsignee());
        //收货人联系电话
        orders.setPhone(one.getPhone());
        //保存收货地址
        orders.setAddress(
                (one.getProvinceName() == null ? "" : one.getProvinceName())
                        + (one.getCityName() == null ? "" : one.getCityName())
                        + (one.getDistrictName() == null ? "" : one.getDistrictName())
                        + (one.getDetail() == null ? "" : one.getDetail())
        );*/
        orderService.save(orders);
        //删除用户购物车数据
        shoppingCartService.remove(shopoingLqw);
        return R.success("下单成功");
    }

    //移动端分页查询订单
    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize) {
        //分页构造
        Page<Orders> page1 = new Page(page, pageSize);
        orderService.page(page1);
        List<Orders> records = page1.getRecords();
       /* //用户id
        Long userId = BaseContext.getCurrentId();*/
        int size = records.size();
      /*  //订单集合
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Orders::getOrderTime);
        lqw.eq(Orders::getUserId, userId);
        List<Orders> orderList = orderService.list(lqw);*/

       /* //ArrayList<OrdersDto> ordersDtos1 = new ArrayList<>();
        //赋值bean
        //List newList = (List) oldList.stream().collect(Collectors.toList());*/

        List<OrdersDto> ordersDtos = records.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            //查询订单明细
            //订单id
            //Long ordersId = ordersDto.getId();
            //查询明细
            LambdaQueryWrapper<OrderDetail> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> orderDetailList = orderDetailService.list(lqw1);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());

        /*int size = ordersDtos.size();
        for (OrdersDto ordersDto : ordersDtos) {
            //查询订单明细
            //订单id
            Long ordersId = ordersDto.getId();
            //查询明细
            LambdaQueryWrapper<OrderDetail> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(OrderDetail::getOrderId, ordersId);
            List<OrderDetail> orderDetailList = orderDetailService.list(lqw1);
            ordersDto.setOrderDetails(orderDetailList);
        }*/

       /* //添加查询条件
        LambdaQueryWrapper<Orders> lqw1 = new LambdaQueryWrapper<>();
        lqw1.orderByAsc(Orders::getOrderTime);
        lqw1.eq(Orders::getUserId, userId);
        //for (OrdersDto ordersDto : ordersDtos) {
        //    ordersDto.getId();
        //    lqw1.eq(Orders::getId,ordersDto.getId());
        //}*/

        //orderService.page(page1, lqw1);
        //System.out.println(page1);
        //return R.success(ordersDtos);

        HashMap<Object, Object> Map = new HashMap<>();
        long total = page1.getTotal();
        Map.put("total", total);
        Map.put("records", ordersDtos);

        return R.success(Map);
    }

    //后台分页查询订单
    @GetMapping("/page")
    public R page1(int page, int pageSize, Long number,
                   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
                   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        //分页构造
        Page page1 = new Page(page, pageSize);

    /*    //用户id
        Long userId = BaseContext.getCurrentId();


        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Orders::getOrderTime);
        lqw.eq(Orders::getUserId, userId);
        List<Orders> orderList = orderService.list(lqw);

        //ArrayList<OrdersDto> ordersDtos1 = new ArrayList<>();
        //赋值bean
        //List newList = (List) oldList.stream().collect(Collectors.toList());

        List<OrdersDto> ordersDtos = orderList.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            return ordersDto;
        } ).collect(Collectors.toList());

        int size = ordersDtos.size();


        for (OrdersDto ordersDto : ordersDtos) {
            //查询订单明细
            //订单id
            Long ordersId = ordersDto.getId();
            //查询明细
            LambdaQueryWrapper<OrderDetail> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(OrderDetail::getOrderId, ordersId);
            List<OrderDetail> orderDetailList = orderDetailService.list(lqw1);
            ordersDto.setOrderDetails(orderDetailList);
        }*/
        //添加查询条件
        LambdaQueryWrapper<Orders> lqw1 = new LambdaQueryWrapper<>();
        lqw1.orderByAsc(Orders::getOrderTime);
        System.out.println(number);
        if (number != null) {
            lqw1.eq(Orders::getId, number);
        }
        System.out.println(beginTime);
        if (beginTime != null && endTime != null) {
            lqw1.between(Orders::getOrderTime, beginTime, endTime);
        }

        //lqw1.eq(Orders::getUserId, userId);
        //for (OrdersDto ordersDto : ordersDtos) {
        //    ordersDto.getId();
        //    lqw1.eq(Orders::getId,ordersDto.getId());
        //}
        orderService.page(page1, lqw1);

        System.out.println(page1);
        //return R.success(ordersDtos);
        return R.success(page1);
    }

}